package org.example.cat.demo.order.web;

import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 *
 * @author ld
 * @date 2022/3/27
 */
@Slf4j
@RestController
public class OrderController {
    @Resource
    private RestTemplate restTemplate;

    /**
     * 指向库存服务的接口
     */
    @Value("${order.address:localhost:8084}")
    private String stockAddress;

    /**
     * 指向账户服务的接口
     */
    @Value("${order.address:localhost:8083}")
    private String accountAddress;

    /**
     * 异常测试端口
     */
    private static final int MOCK_PORT = 8765;

    /**
     * 提供下单接口
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("/order")
    public String service2MethodInController() throws InterruptedException {
        Thread.sleep(200);
        // 调用账户服务以及库存服务
        String service3 = restTemplate.getForObject("http://" + accountAddress + "/account", String.class);
        String service4 = restTemplate.getForObject("http://" + stockAddress + "/stock", String.class);
        return String.format("Calling order service[order success] ==> Calling Account Service [%s]  ==> Calling Customer Service [%s]", service3, service4);
    }

    /**
     * 模拟异常超时接口
     * @return
     * @throws InterruptedException
     */
    @RequestMapping("/timeout")
    public String connectionTimeout() throws InterruptedException {
        Transaction t = Cat.newTransaction(CatConstants.TYPE_CALL, "connectionTimeout");
        Thread.sleep(500);
        try {
            log.info("Calling a missing service");
            restTemplate.getForObject("http://localhost:" + MOCK_PORT + "/timeout", String.class);
            return "Should blow up";
        } catch(Exception e) {
            t.setStatus(e);
            Cat.getProducer().logError(e);
            throw e;
        } finally {
            t.complete();
        }
    }
}
